<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url_for('static', path='./styles.css') }}">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <title>Карта</title>
</head>
<body>
    {% include 'header.html' %}

    <main>
        <div id="map" style="width: 100%; height: 840px; z-index:1;"></div>
        <div id="infoBox" class="info-box"></div>
    </main>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const map = L.map('map').setView([55.751244, 37.618423], 5);

            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);

            async function loadRegions() {
                try {
                    const response = await fetch('/region/array');
                    if (response.ok) {
                        const regions = await response.json();
                        renderRegionsOnMap(regions);
                    } else {
                        showMessage('Ошибка загрузки регионов', 'error');
                    }
                } catch (error) {
                    showMessage('Ошибка загрузки регионов: ' + error.message, 'error');
                }
            }

            function renderRegionsOnMap(regions) {
                regions.forEach(region => {
                    const lat = region.latitude;
                    const lon = region.longitude;
                    const regionCircle = L.circle([lat, lon], {
                        color: '#ff7800',
                        fillColor: '#ff7800',
                        fillOpacity: 0.5,
                        radius: 15000
                    }).addTo(map);

                    let popupContent = `<b>${region.name}</b><br>`;
                    if (region.parentRegion) popupContent += `<br>Родительский регион: ${region.parentRegion}`;
                    if (region.regionType) popupContent += `<br>Тип региона: ${region.regionType}`;
                    if (region.accountId) popupContent += `<br>ID добавившего: ${region.accountId}`;
                    popupContent += `<br><br><center><a href="/region?id=${region.id}">Перейти</a></center>`

                    regionCircle.bindPopup(popupContent);

                    regionCircle.on('mouseover', function() {
                        showInfoBox(region);
                    });

                    regionCircle.on('mouseout', function() {
                        hideInfoBox();
                    });

                    regionCircle.on('click', function() {
                        // window.location.href = `/region?id=${region.id}`;
                    });
                });
            }

            function showInfoBox(region) {
                const infoBox = document.getElementById('infoBox');
                infoBox.innerHTML = `<b>${region.name}</b><br>`;
                if (region.parentRegion) infoBox.innerHTML += `Родительский регион: ${region.parentRegion}<br>`;
                if (region.regionType) infoBox.innerHTML += `Тип региона: ${region.regionType}<br>`;
                if (region.accountId) infoBox.innerHTML += `ID добавившего: ${region.accountId}<br>`;
                
                infoBox.innerHTML += "<br>Для перехода нажмите по области региона"
                infoBox.style.display = 'block';
            }

            function hideInfoBox() {
                const infoBox = document.getElementById('infoBox');
                infoBox.style.display = 'none';
            }

            loadRegions();
        });

        function showMessage(message, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = message;
            messageDiv.className = `message ${type}`;
            messageDiv.style.display = 'block';
            setTimeout(() => {
                messageDiv.style.display = 'none';
            }, 5000);
        }
    </script>
</body>
</html>